<template>
    <!--查询栏-->
    <a-card :bodyStyle="{padding: '16px 12px'}" style="margin-bottom: 12px">
        <a-row type="flex" justify="space-between">
            <a-col :span="22">
                <a-form :model="queryParams"
                        ref="queryFormRef"
                        layout="inline"
                        autocomplete="off">
                    <#list table.columns as column>
                    <#if (column.uiComponentType??)>
                    <a-form-item label="${column.uiLabelName}:" name="${column.fieldName}">
                        <#if (column.uiComponentType == "input" || column.uiComponentType == "textarea")>
                        <a-input v-model:value="queryParams.${column.fieldName}" allow-clear style="width: 160px"/>
                        </#if>
                        <#if (column.uiComponentType == "select" || column.uiComponentType == "radio"
                            ||column.uiComponentType == "checkbox" || column.uiComponentType == "switch")>
                        <a-select v-model:value="queryParams.${column.fieldName}" allow-clear style="width: 120px">
                            <#list column.uiKeyValues?keys as key>
                            <a-select-option :value="${key}">
                                ${column.uiKeyValues[key]}
                            </a-select-option>
                            </#list>
                        </a-select>
                        </#if>
                        <#if (column.uiComponentType == "input-number")>
                        <a-input-number v-model:value="queryParams.${column.fieldName}"
                                        :min="0"
                                        :max="100"
                                        :step="1"
                                        allow-clear
                                        style="width: 120px"/>
                        </#if>
                    </a-form-item>
                    </#if>
                    </#list>
                    <a-form-item>
                        <a-space>
                            <a-button type="primary" ghost @click="onQueryList">
                                <search-outlined/>
                                查询
                            </a-button>
                            <a-button @click="resetQueryForm">
                                <reload-outlined/>
                                重置
                            </a-button>
                        </a-space>
                    </a-form-item>
                </a-form>
            </a-col>
            <a-col :span="2">
                <a-button type="primary" style="float: right" @click="showCreateDialog">
                    <plus-outlined/>
                    新建
                </a-button>
            </a-col>
        </a-row>
    </a-card>

    <!--列表-->
    <a-table :data-source="dataList"
             :columns="columns"
             size="middle"
             :pagination="pagination"
             @change="onChangePage">
        <template #bodyCell="{ column, record }">
            <#list table.columns as column>
            <#if column.uiComponentType?? &&
                 (column.uiComponentType == "select" || column.uiComponentType == "radio"
                 ||column.uiComponentType == "checkbox")>
            <template v-if="column.key === '${column.fieldName}'">
                {{${column.columnName}_map[record.${column.fieldName}]}}
            </template>
            </#if>
            <#if (column.uiComponentType?? && column.uiComponentType == "switch")>
            <template v-if="column.key === '${column.fieldName}'">
                {{${column.columnName}_map[record.${column.fieldName} ? 1 : 0]}}
            </template>
            </#if>
            </#list>
            <template v-if="column.key === 'action'">
                <a @click="showUpdateDialog(record)">修改</a>
                <a-divider type="vertical"/>
                <a-popconfirm
                        title="确定要删除吗?"
                        ok-text="确定"
                        cancel-text="取消"
                        @confirm="submitDeleteData(record.id)">
                    <a href="#">删除</a>
                </a-popconfirm>
            </template>
        </template>
    </a-table>

    <!--新建对话框-->
    <a-modal v-model:visible="createDialogVisible"
             title="新建"
             :width="700"
             :maskClosable="false"
             ok-text="确认"
             cancel-text="取消"
             @ok="submitCreateForm">
        <a-form :model="createParams"
                ref="createFormRef"
                autocomplete="off"
                :label-col="{ span: 6 }"
                :wrapper-col="{ span: 14 }">
            <#list table.columns as column>
            <#if (column.uiComponentType??)>
            <a-form-item label="${column.uiLabelName}:"
                         <#if (!column.isAllowNull)>
                         :rules="[{ required: true, message: '请输入${column.uiLabelName}', trigger: 'blur' },]"
                         </#if>
                         name="${column.fieldName}">
                <#if (column.uiComponentType == "input")>
                <a-input v-model:value="createParams.${column.fieldName}" allow-clear/>
                </#if>
                <#if (column.uiComponentType == "select")>
                <a-select v-model:value="createParams.${column.fieldName}" allow-clear>
                    <#list column.uiKeyValues?keys as key>
                    <a-select-option :value="${key}">
                        ${column.uiKeyValues[key]}
                    </a-select-option>
                    </#list>
                </a-select>
                </#if>
                <#if (column.uiComponentType == "textarea")>
                <a-textarea v-model:value="createParams.${column.fieldName}" :rows="3" allow-clear/>
                </#if>
                <#if (column.uiComponentType == "radio")>
                <a-radio-group v-model:value="createParams.${column.fieldName}" allow-clear>
                    <#list column.uiKeyValues?keys as key>
                    <a-radio :value="${key}">
                        ${column.uiKeyValues[key]}
                    </a-radio>
                    </#list>
                </a-radio-group>
                </#if>
                <#if (column.uiComponentType == "checkbox")>
                <a-checkbox-group v-model:value="createParams.${column.fieldName}" allow-clear>
                    <#list column.uiKeyValues?keys as key>
                    <a-checkbox :value="${key}">
                        ${column.uiKeyValues[key]}
                    </a-checkbox>
                    </#list>
                </a-checkbox-group>
                </#if>
                <#if (column.uiComponentType == "switch")>
                <a-switch v-model:checked="createParams.${column.fieldName}"/>
                </#if>
                <#if (column.uiComponentType == "input-number")>
                <a-input-number v-model:value="createParams.${column.fieldName}"
                                :min="0"
                                :max="100"
                                :step="1"
                                allow-clear/>
                </#if>
            </a-form-item>
            </#if>
            </#list>
        </a-form>
    </a-modal>

    <!--修改对话框-->
    <a-modal v-model:visible="updateDialogVisible"
             title="修改"
             :width="700"
             :maskClosable="false"
             ok-text="确认"
             cancel-text="取消"
             @ok="submitUpdateForm">
        <a-form :model="updateParams"
                ref="updateFormRef"
                autocomplete="off"
                :label-col="{ span: 6 }"
                :wrapper-col="{ span: 14 }">
            <#list table.columns as column>
            <#if (column.uiComponentType??)>
            <a-form-item label="${column.uiLabelName}:"
                         <#if (!column.isAllowNull)>
                         :rules="[{ required: true, message: '请输入${column.uiLabelName}', trigger: 'blur' },]"
                         </#if>
                         name="${column.fieldName}">
                <#if (column.uiComponentType == "input")>
                <a-input v-model:value="updateParams.${column.fieldName}" allow-clear/>
                </#if>
                <#if (column.uiComponentType == "select")>
                <a-select v-model:value="updateParams.${column.fieldName}" allow-clear>
                    <#list column.uiKeyValues?keys as key>
                    <a-select-option :value="${key}">
                        ${column.uiKeyValues[key]}
                    </a-select-option>
                    </#list>
                </a-select>
                </#if>
                <#if (column.uiComponentType == "textarea")>
                <a-textarea v-model:value="updateParams.${column.fieldName}" :rows="3" allow-clear/>
                </#if>
                <#if (column.uiComponentType == "radio")>
                <a-radio-group v-model:value="updateParams.${column.fieldName}" allow-clear>
                    <#list column.uiKeyValues?keys as key>
                    <a-radio :value="${key}">
                        ${column.uiKeyValues[key]}
                    </a-radio>
                    </#list>
                </a-radio-group>
                </#if>
                <#if (column.uiComponentType == "checkbox")>
                <a-checkbox-group v-model:value="updateParams.${column.fieldName}" allow-clear>
                    <#list column.uiKeyValues?keys as key>
                    <a-checkbox :value="${key}">
                        ${column.uiKeyValues[key]}
                    </a-checkbox>
                    </#list>
                </a-checkbox-group>
                </#if>
                <#if (column.uiComponentType == "switch")>
                <a-switch v-model:checked="updateParams.${column.fieldName}"/>
                </#if>
                <#if (column.uiComponentType == "input-number")>
                <a-input-number v-model:value="updateParams.${column.fieldName}"
                                :min="0"
                                :max="100"
                                :step="1"
                                allow-clear/>
                </#if>
            </a-form-item>
            </#if>
            </#list>
        </a-form>
    </a-modal>
</template>

<script>
    import {defineComponent, ref, toRefs, reactive, onMounted} from 'vue';
    import {message} from 'ant-design-vue';
    import WebApi from "@/webapi/WebApi"

    const columns = [
        <#list table.columns as column>
        <#if !column.isDeletedColumn>
        {
            title: '${column.uiLabelName}',
            dataIndex: '${column.fieldName}',
            key: '${column.fieldName}',
            minWidth: 140,
            <#if column.uiComponentType?? && (column.uiComponentType == "textarea")>
            ellipsis: true,
            </#if>
        },
        </#if>
        </#list>
        {
            title: '操作',
            key: 'action',
            width: 150,
        },
    ];

    <#list table.columns as column>
    <#if column.uiComponentType?? &&
         (column.uiComponentType == "select" || column.uiComponentType == "radio"
         ||column.uiComponentType == "checkbox" || column.uiComponentType == "switch")>
    const ${column.columnName}_map = {
        <#list column.uiKeyValues?keys as key>
        ${key}: '${column.uiKeyValues[key]}',
        </#list>
    };

    </#if>
    </#list>
    export default defineComponent({
        components: {},
        setup() {
            const state = reactive({
                queryParams: {},
                dataList: [],
                pagination: {
                    current: 1,
                    total: 0,
                    pageSize: 20,
                    showSizeChanger: false,
                    pageSizeOptions: ["10", "20", "50", "100"],
                    showTotal: total => '共 ' + total + ' 条数据',
                },
                createDialogVisible: false,
                createParams: {},
                updateDialogVisible: false,
                updateParams: {},
            });
            const queryFormRef = ref();
            const createFormRef = ref();
            const updateFormRef = ref();

            const queryList = () => {
                const pageable = {
                    page: state.pagination.current,
                    size: state.pagination.pageSize,
                    params: state.queryParams
                };
                WebApi.page${table.className}(pageable).then(
                    (resp) => {
                        const data = resp.data.data;
                        state.dataList = data.list;
                        state.pagination.total = data.total;
                    }
                );
            };

            onMounted(() => {
                queryList();
            });

            const onQueryList = () => {
                state.pagination.current = 1;
                queryList();
            };

            const onChangePage = (page) => {
                state.pagination.current = page.current;
                queryList();
            };

            const resetQueryForm = () => {
                queryFormRef.value.resetFields();
            };

            const showCreateDialog = () => {
                state.createParams = {};
                state.createDialogVisible = true;
                createFormRef.value?.clearValidate();
            };

            const submitCreateForm = async () => {
                try {
                    await createFormRef.value.validateFields();
                    const params = {
                        ...state.createParams,
                    };
                    WebApi.create${table.className}(params).then(
                        () => {
                            state.createDialogVisible = false;
                            queryList();
                            message.success('保存数据成功!');
                        }
                    );
                } catch (error) {
                    console.log('Validate failed: ', error);
                }
            };

            const showUpdateDialog = (record) => {
                state.updateParams = Object.assign({},record);
                state.updateDialogVisible = true;
                updateFormRef.value?.clearValidate();
            };

            const submitUpdateForm = async () => {
                try {
                    await updateFormRef.value.validateFields();
                    const params = {
                        ...state.updateParams,
                    };
                    WebApi.update${table.className}(params).then(
                        () => {
                            state.updateDialogVisible = false;
                            queryList();
                            message.success('保存数据成功!');
                        }
                    );
                } catch (error) {
                    console.log('Validate failed: ', error);
                }
            };

            const submitDeleteData = (id) => {
                WebApi.delete${table.className}(id).then(
                    () => {
                        queryList();
                        message.success('删除数据成功!');
                    }
                );
            };

            return {
                <#list table.columns as column>
                <#if column.uiComponentType?? &&
                     (column.uiComponentType == "select" || column.uiComponentType == "radio"
                     ||column.uiComponentType == "checkbox" || column.uiComponentType == "switch")>
                ${column.columnName}_map,
                </#if>
                </#list>
                columns,
                ...toRefs(state),
                queryFormRef,
                createFormRef,
                updateFormRef,
                onQueryList,
                onChangePage,
                resetQueryForm,
                showCreateDialog,
                submitCreateForm,
                showUpdateDialog,
                submitUpdateForm,
                submitDeleteData
            };
        },
    });
</script>

<style lang="less" scoped>

    .query-bar {
        margin-bottom: 8px;

        .ant-form {
            .ant-form-item {
                margin-bottom: 0;
            }
        }
    }

</style>